import classnames from 'classnames'
import React, { useEffect, useRef, useState } from 'react'
import Icon from '../Icon'
import styles from './index.module.scss'

/**
 * 拥有懒加载特性的图片组件
 * @param {String} props.src 图片地址
 * @param {String} props.className 样式类
 */
type Props = {
  src: string
  className?: string
}
const Image = ({ src, className }: Props) => {
  const [error, setError] = useState(false)
  // 是否正在加载
  const [load, setLoad] = useState(true)
  // 对图片元素的引用
  const imgRef = useRef<HTMLImageElement>(null)

  useEffect(() => {
    const ob = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) {
        // 可见
        // console.log('可见', entries)
        // 1. 设置 src
        // imgRef.current!.src = imgRef.current!.getAttribute('data-src')!
        if (imgRef.current) {
          const src = imgRef.current.getAttribute('data-src')
          if (src) {
            imgRef.current.src = src
          }
        }
        // 2. 停止观察
        ob.disconnect()
      }
    })

    // 观察
    ob.observe(imgRef.current!)
    return () => {
      ob.disconnect()
    }
  }, [])

  return (
    <div className={classnames(styles.root, className)}>
      {/* 正在加载时显示的内容 */}
      {load && (
        <div className="image-icon">
          <Icon type="iconphoto" />
        </div>
      )}

      {/* 加载出错时显示的内容 */}
      {error && (
        <div className="image-icon">
          <Icon type="iconphoto-fail" />
        </div>
      )}

      {/* 加载成功时显示的内容 */}
      {
        <img
          onLoad={() => setLoad(false)}
          onError={() => setError(true)}
          alt=""
          data-src={src}
          ref={imgRef}
        />
      }
    </div>
  )
}

export default Image
